<%--
  Created by IntelliJ IDEA.
  User: Fan
  Date: 2025/10/13
  Time: 09:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<jsp:include page="header.jsp"/>

<style>
    :root {
        --bs-primary: #3b7ddd;
        --bs-primary-rgb: 59, 125, 221;
        --bs-success: #1cbb8c;
        --bs-success-rgb: 28, 187, 140;
        --bs-danger: #fc5b69;
        --bs-danger-rgb: 252, 91, 105;
        --bs-warning: #f7b84b;
        --bs-warning-rgb: 247, 184, 75;
        --bs-light-bg: #f5f7fa;
    }

    .card {
        border-radius: 0.5rem;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        border: none;
        margin-bottom: 1.5rem;
    }

    .card-header {
        background-color: #fff;
        border-bottom: 1px solid #eaeef1;
        padding: 1rem 1.25rem;
        font-weight: 600;
        color: #2c3e50;
    }

    .table-container {
        background-color: #fff;
        border-radius: 0.5rem;
        overflow: hidden;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    }

    .table th {
        background-color: var(--bs-light-bg);
        color: #2c3e50;
        font-weight: 600;
        padding: 0.75rem 1rem;
        border-top: none;
    }

    .table td {
        padding: 0.75rem 1rem;
        vertical-align: middle;
    }

    .status-badge {
        padding: 0.35em 0.65em;
        border-radius: 0.25rem;
        font-size: 0.75em;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .bg-enabled {
        background-color: rgba(var(--bs-success-rgb), 0.15);
        color: var(--bs-success);
    }

    .bg-disabled {
        background-color: rgba(var(--bs-danger-rgb), 0.15);
        color: var(--bs-danger);
    }

    .action-btn {
        padding: 0.25rem 0.5rem;
        border-radius: 0.25rem;
        font-size: 0.875rem;
    }
    .search-box {
        position: relative;
        margin-bottom: 0.5rem;
    }

    .search-box .form-control {
        border-radius: 2rem;
        padding-left: 2.75rem;
        padding-right: 1rem;
        height: calc(2.5rem + 2px);
        border: 2px solid #e9ecef;
        transition: border-color 0.2s ease, box-shadow 0.2s ease;
    }

    .search-box .form-control:focus {
        border-color: var(--bs-primary);
        box-shadow: 0 0 0 0.25rem rgba(59, 125, 221, 0.15);
    }

    .search-box .bi {
        position: absolute;
        left: 1.25rem;
        top: 50%;
        transform: translateY(-50%);
        color: #6c757d;
        z-index: 10;
        font-size: 1.1rem;
    }

    .search-actions {
        display: flex;
        gap: 0.75rem;
        flex-wrap: wrap;
        align-items: center;
    }

    /* 动画效果 */
    .fade-in {
        animation: fadeIn 0.3s ease-in;
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
</style>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">老师管理系统</h1>
</div>

<c:if test="${not empty teacherSearchText}">
    <div class="card mb-3">
        <div class="card-body d-flex justify-content-between align-items-center flex-wrap">
            <div class="flex-grow-1 mb-2 mb-md-0">
                <h5 class="card-title">
                    <i class="bi bi-search me-2"></i>搜索结果
                </h5>
                <p class="mb-0 text-muted">
                    <span class="mx-2">|</span>
                    找到 <strong>${page.totalCount}</strong> 个老师
                </p>
            </div>
        </div>
    </div>
</c:if>

<!-- 卡片中的搜索部分 -->
<div class="card fade-in">
    <div class="card-body">
        <form action="${pageContext.request.contextPath}/teamanage/searchTeacher" method="get" id="searchForm">
            <div class="row g-3 align-items-center">
                <div class="col-md-3">
                    <select class="form-select" name="searchType">
                        <option value="name" ${searchType eq 'name' ? 'selected' : ''}>按姓名搜索</option>
                        <option value="id" ${searchType eq 'id' ? 'selected' : ''}>按ID搜索</option>
                        <option value="type" ${searchType eq 'type' ? 'selected' : ''}>按教职工类型搜索</option>
                        <option value="phone" ${searchType eq 'phone' ? 'selected' : ''}>按电话搜索</option>
                    </select>
                </div>
                <div class="col-md-5">
                    <div class="search-box">
                        <i class="bi bi-search"></i>
                        <input type="text" class="form-control" placeholder="输入搜索内容"
                               id="teacherSearchInput" name="teacherSearchText" value="${teacherSearchText}">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="search-actions">
                        <button class="btn btn-primary" type="submit" id="searchBtn">
                            <i class="bi bi-search"></i> 查询
                        </button>
                        <button class="btn btn-success" type="button" data-bs-toggle="modal" data-bs-target="#addTeacherModal">
                            <i class="bi bi-plus-circle"></i> 添加老师
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>


<!-- 数据表格 -->
<div class="table-container fade-in">
    <div class="table-responsive">
        <table class="table table-hover" id="teacherTable">
            <thead>
            <tr>
                <th scope="col">ID</th>
                <th scope="col">姓名</th>
                <th scope="col">电话</th>
                <th scope="col">教职工类型</th>
                <th scope="col">状态</th>
                <th scope="col">操作</th>
            </tr>
            </thead>
            <c:if test="${empty page.items}">
                <tr>
                    <td colspan="5" class="text-center">暂无老师数据</td>
                </tr>
            </c:if>
            <c:forEach items="${page.items}" var="teacher" varStatus="status">
                <tr>
                    <td>${(page.pageIndex - 1) * page.pageSize + status.index + 1}</td>
                    <td>${teacher.name}</td>
                    <td>${teacher.phone}</td>
                    <td>
                        <c:choose>
                            <c:when test="${not empty teacher.typeName}">
                                ${teacher.typeName}
                            </c:when>
                            <c:otherwise>
                                未指定
                            </c:otherwise>
                        </c:choose>
                    </td>
                    <td>
                        <c:choose>
                            <c:when test="${teacher.state}">
                                <span class="status-badge bg-enabled">启用</span>
                            </c:when>
                            <c:otherwise>
                                <span class="status-badge bg-disabled">禁用</span>
                            </c:otherwise>
                        </c:choose>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary action-btn"
                                onclick="window.showEditModal(${teacher.id}, '${teacher.name}', '${teacher.phone}', ${teacher.state}, '${teacher.type}')">
                            <i class="bi bi-pencil me-1"></i>编辑
                        </button>
                        <button class="btn btn-sm btn-outline-danger action-btn"
                                onclick="showDeleteModal(${teacher.id}, '${teacher.name}')">
                            <i class="bi bi-trash me-1"></i>删除
                        </button>
                    </td>
                </tr>
            </c:forEach>
            </tbody>
        </table>
        <jsp:include page="pagination.jsp">
            <jsp:param name="teacherSearchText" value="${teacherSearchText}" />
            <jsp:param name="searchType" value="${searchType}" />
        </jsp:include>
    </div>
</div>

<!-- 添加老师 Modal -->
<div class="modal fade" id="addTeacherModal" tabindex="-1" aria-labelledby="addTeacherModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addTeacherModalLabel">添加老师</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addTeacherForm">
                    <div class="mb-3">
                        <label for="teacherName" class="form-label">姓名</label>
                        <input type="text" class="form-control" id="teacherName" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label for="teacherPhone" class="form-label">电话</label>
                        <input type="tel" class="form-control" id="teacherPhone" name="phone" required>
                    </div>
                    <div class="mb-3">
                        <label for="teacherTypeId" class="form-label">教职工类型</label>
                        <select class="form-select" id="teacherTypeId" name="typeId" required>
                            <option value="">请选择类型</option>
                            <c:forEach items="${roles}" var="role">
                                <option value="${role.id}">${role.roleName}</option>
                            </c:forEach>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="teacherState" class="form-label">状态</label>
                        <select class="form-select" id="teacherState" name="state" required>
                            <option value="true" selected>启用</option>
                            <option value="false">禁用</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveTeacherBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑老师 Modal -->
<div class="modal fade" id="editTeacherModal" tabindex="-1" aria-labelledby="editTeacherModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editTeacherModalLabel">编辑老师</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editTeacherForm">
                    <input type="hidden" id="editTeacherId" name="id">
                    <div class="mb-3">
                        <label for="editTeacherName" class="form-label">姓名</label>
                        <input type="text" class="form-control" id="editTeacherName" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label for="editTeacherPhone" class="form-label">电话</label>
                        <input type="tel" class="form-control" id="editTeacherPhone" name="phone" required>
                    </div>
                    <div class="mb-3">
                        <label for="editTeacherTypeId" class="form-label">教职工类型</label>
                        <select class="form-select" id="editTeacherTypeId" name="typeId" required>
                            <option value="">请选择类型</option>
                            <c:forEach items="${roles}" var="role">
                                <option value="${role.id}">${role.roleName}</option>
                            </c:forEach>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="editTeacherState" class="form-label">状态</label>
                        <select class="form-select" id="editTeacherState" name="state" required>
                            <option value="true">启用</option>
                            <option value="false">禁用</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveEditTeacherBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认Modal -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmModalLabel"
     aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteConfirmModalLabel">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除这个老师吗？此操作不可恢复！</p>
                <p>老师ID: <span id="deleteTeacherId"></span></p>
                <p>老师姓名: <span id="deleteTeacherName"></span></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确认删除</button>
            </div>
        </div>
    </div>
</div>

<!-- 操作结果Modal -->
<div class="modal fade" id="resultModal" tabindex="-1" aria-labelledby="resultModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="resultModalLabel">操作结果</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body text-center">
                <i id="resultIcon" class="bi" style="font-size: 3rem;"></i>
                <h5 id="resultTitle" class="mt-3"></h5>
                <p id="resultMessage" class="mb-0"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">确定</button>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        // 获取表单和输入元素
        const searchForm = document.getElementById('searchForm');
        const teacherSearchInput = document.getElementById('teacherSearchInput');
        const searchBtn = document.getElementById('searchBtn');

        // 为老师搜索框添加回车事件
        if (teacherSearchInput) {
            teacherSearchInput.addEventListener('keyup', function (e) {
                if (e.key === 'Enter') {
                    const searchText = teacherSearchInput.value.trim();
                    if (searchText !== '') {
                        searchForm.submit();
                    }
                }
            });
        }

        // 点击查询按钮时触发表单提交
        if (searchBtn) {
            searchBtn.addEventListener('click', function (e) {
                e.preventDefault();
                const searchText = teacherSearchInput ? teacherSearchInput.value.trim() : '';
                if (searchText !== '') {
                    searchForm.submit();
                }
            });
        }

        // 添加老师功能
        function addTeacher() {
            const form = document.getElementById('addTeacherForm');
            const formData = new FormData(form);

            // 将FormData转换为JSON对象
            const teacherData = {};
            formData.forEach((value, key) => {
                // 处理状态字段，将字符串转换为布尔值
                if (key === 'state') {
                    teacherData[key] = value === 'true';
                } else if (key === 'typeId') {
                    teacherData['type'] = value; // 将typeId映射为type
                } else {
                    teacherData[key] = value;
                }
            });

            // 使用Ajax发送数据到后端
            fetch('${pageContext.request.contextPath}/teamanage/addTeacher', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify(teacherData)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应异常: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        // 显示成功消息
                        showAutoDismissModal(data.message, true);
                        // 关闭Modal
                        const addModal = bootstrap.Modal.getInstance(document.getElementById('addTeacherModal'));
                        if (addModal) {
                            addModal.hide();
                        }
                        // 重置表单
                        form.reset();
                        // 重新加载页面数据
                        setTimeout(function () {
                            location.reload();
                        }, 1500);
                    } else {
                        // 显示错误消息
                        showAutoDismissModal(data.message, false);
                    }
                })
                .catch(error => {
                    console.error('添加老师出错:', error);
                    showAutoDismissModal('添加老师过程中发生错误，请重试', false);
                });
        }

        // 显示编辑模态框
        function showEditModal(teacherId, teacherName, teacherPhone, teacherState,teacherType) {
            // 设置表单字段值
            document.getElementById('editTeacherId').value = teacherId;
            document.getElementById('editTeacherName').value = teacherName;
            document.getElementById('editTeacherPhone').value = teacherPhone;
            document.getElementById('editTeacherState').value = teacherState;
            document.getElementById('editTeacherTypeId').value = teacherType;

            // 显示模态框
            const editModal = new bootstrap.Modal(document.getElementById('editTeacherModal'));
            editModal.show();
        }

        // 编辑老师功能
        function editTeacher() {
            const form = document.getElementById('editTeacherForm');
            const formData = new FormData(form);

            // 将FormData转换为JSON对象
            const teacherData = {};
            formData.forEach((value, key) => {
                // 处理状态字段，将字符串转换为布尔值
                if (key === 'state') {
                    teacherData[key] = value === 'true';
                } else if (key === 'id') {
                    teacherData[key] = parseInt(value);
                } else if (key === 'typeId') {
                    teacherData['type'] = value; // 将typeId映射为type
                } else {
                    teacherData[key] = value;
                }
            });

            // 使用Ajax发送数据到后端
            fetch('${pageContext.request.contextPath}/teamanage/updateTeacher', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify(teacherData)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应异常: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        // 显示成功消息
                        showAutoDismissModal(data.message, true);
                        // 关闭Modal
                        const editModal = bootstrap.Modal.getInstance(document.getElementById('editTeacherModal'));
                        if (editModal) {
                            editModal.hide();
                        }
                        // 重新加载页面数据
                        setTimeout(function () {
                            location.reload();
                        }, 1500);
                    } else {
                        // 显示错误消息
                        showAutoDismissModal(data.message, false);
                    }
                })
                .catch(error => {
                    console.error('编辑老师出错:', error);
                    showAutoDismissModal('编辑老师过程中发生错误，请重试', false);
                });
        }

        // 显示自动消失的Modal
        function showAutoDismissModal(message, isSuccess) {
            const modalElement = document.getElementById('resultModal');
            const resultIcon = document.getElementById('resultIcon');
            const resultTitle = document.getElementById('resultTitle');
            const resultMessage = document.getElementById('resultMessage');

            // 设置图标和样式
            if (isSuccess) {
                resultIcon.className = 'bi bi-check-circle-fill text-success';
                resultTitle.textContent = '成功';
                resultTitle.className = 'mt-3 text-success';
            } else {
                resultIcon.className = 'bi bi-exclamation-triangle-fill text-danger';
                resultTitle.textContent = '错误';
                resultTitle.className = 'mt-3 text-danger';
            }

            // 设置消息内容
            resultMessage.textContent = message;

            // 显示Modal
            const modal = new bootstrap.Modal(modalElement);
            modal.show();

            // 3秒后自动关闭
            setTimeout(function () {
                modal.hide();
            }, 3000);
        }

        // 检查URL参数，如果有成功或错误消息则显示
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.has('success')) {
            showAutoDismissModal(decodeURIComponent(urlParams.get('success')), true);
            // 清理URL参数，避免刷新时重复显示
            setTimeout(function () {
                const url = new URL(window.location);
                url.searchParams.delete('success');
                window.history.replaceState({}, document.title, url);
            }, 3500);
        } else if (urlParams.has('error')) {
            showAutoDismissModal(decodeURIComponent(urlParams.get('error')), false);
            // 清理URL参数，避免刷新时重复显示
            setTimeout(function () {
                const url = new URL(window.location);
                url.searchParams.delete('error');
                window.history.replaceState({}, document.title, url);
            }, 3500);
        }

        // 显示删除确认Modal
        function showDeleteModal(teacherId, teacherName) {
            document.getElementById('deleteTeacherId').textContent = teacherId;
            document.getElementById('deleteTeacherName').textContent = teacherName;

            // 设置确认删除按钮的事件
            const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
            if (confirmDeleteBtn) {
                // 移除所有现有的事件监听器
                const newButton = confirmDeleteBtn.cloneNode(true);
                confirmDeleteBtn.parentNode.replaceChild(newButton, confirmDeleteBtn);

                // 添加新的点击事件
                newButton.addEventListener('click', function () {
                    deleteTeacher(teacherId);
                });
            }

            // 显示Modal
            const deleteModal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
            deleteModal.show();
        }

        // 删除老师功能
        function deleteTeacher(teacherId) {
            // 关闭确认Modal
            const deleteModal = bootstrap.Modal.getInstance(document.getElementById('deleteConfirmModal'));
            if (deleteModal) {
                deleteModal.hide();
            }

            // 使用Ajax发送删除请求
            fetch('${pageContext.request.contextPath}/teamanage/deleteTeacher?id=' + teacherId, {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Content-Type': 'application/json'
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应异常: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        // 显示成功消息
                        showAutoDismissModal(data.message, true);
                        // 重新加载页面数据
                        setTimeout(function () {
                            location.reload();
                        }, 1500);
                    } else {
                        // 显示错误消息
                        showAutoDismissModal(data.message, false);
                    }
                })
                .catch(error => {
                    console.error('删除出错:', error);
                    showAutoDismissModal('删除过程中发生错误，请重试', false);
                });
        }

        // 将showDeleteModal函数暴露到全局作用域，以便在HTML中调用
        window.showDeleteModal = showDeleteModal;
        window.showEditModal = showEditModal;
        // 为保存按钮添加事件监听器
        document.getElementById('saveTeacherBtn').addEventListener('click', addTeacher);
        // 为保存编辑按钮添加事件监听器
        document.getElementById('saveEditTeacherBtn').addEventListener('click', editTeacher);
    });
</script>
<jsp:include page="footer.jsp"/>
